package com.fhz.module_user.ui.login;

import android.app.Activity;

import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.appcompat.app.AppCompatActivity;
import androidx.room.RoomDatabase;

import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.bumptech.glide.request.RequestOptions;
import com.fhz.core_lib.base.AppManager;
import com.fhz.core_lib.base.BaseResponse;
import com.fhz.core_lib.dao.database.UserDatabase;
import com.fhz.core_lib.entity.LoggedInUser;
import com.fhz.core_lib.router.RouterActivityPath;
import com.fhz.core_lib.utils.ApiResponse;
import com.fhz.core_lib.utils.ImageLoader;
import com.fhz.core_lib.utils.SPUtils;
import com.fhz.module_user.R;
import com.fhz.module_user.ui.login.LoginViewModel;
import com.fhz.module_user.ui.login.LoginViewModelFactory;
import com.fhz.module_user.databinding.ActivityLoginBinding;

import jp.wasabeef.glide.transformations.BlurTransformation;
@Route(path = RouterActivityPath.User.PAGER_LOGIN)
public class LoginActivity extends AppCompatActivity {

    private LoginViewModel loginViewModel;
    private ActivityLoginBinding binding;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityLoginBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        Glide.with(this).load("http://lmg.jj20.com/up/allimg/tp06/19121014140S607-0-lp.jpg")
                .apply(new RequestOptions().optionalTransform(new BlurTransformation(25)))
                .into(binding.test);

        loginViewModel = new ViewModelProvider(this, new LoginViewModelFactory())
                .get(LoginViewModel.class);

        final EditText usernameEditText = binding.username;
        final EditText passwordEditText = binding.password;
        final Button loginButton = binding.login;
        final ProgressBar loadingProgressBar = binding.loading;

        loginViewModel.getLoginFormState().observe(this, new Observer<LoginFormState>() {
            @Override
            public void onChanged(@Nullable LoginFormState loginFormState) {
                if (loginFormState == null) {
                    return;
                }
                loginButton.setEnabled(loginFormState.isDataValid());
                if (loginFormState.getUsernameError() != null) {
                    usernameEditText.setError(getString(loginFormState.getUsernameError()));
                }
                if (loginFormState.getPasswordError() != null) {
                    passwordEditText.setError(getString(loginFormState.getPasswordError()));
                }
            }
        });


        TextWatcher afterTextChangedListener = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // ignore
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // ignore
            }

            @Override
            public void afterTextChanged(Editable s) {
                loginViewModel.loginDataChanged(usernameEditText.getText().toString(),
                        passwordEditText.getText().toString());
            }
        };
        usernameEditText.addTextChangedListener(afterTextChangedListener);
        passwordEditText.addTextChangedListener(afterTextChangedListener);
        passwordEditText.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                String name = usernameEditText.getText().toString();
//
            }
            return false;
        });

        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loadingProgressBar.setVisibility(View.VISIBLE);
                loginViewModel.login(usernameEditText.getText().toString(), passwordEditText.getText().toString()).observe(LoginActivity.this, new Observer<ApiResponse<LoggedInUser>>() {
                    @Override
                    public void onChanged(ApiResponse<LoggedInUser> loggedInUserApiResponse) {
                        LoggedInUser userInfo = loggedInUserApiResponse.getData();

                        if(userInfo != null){
                            userInfo.getNickname();
                            //存入到sp中--可以考虑加密一下
                            SPUtils.getInstance().put(SPUtils.NICKNAME,userInfo.getNickname());
                            SPUtils.getInstance().put(SPUtils.TOKEN,loggedInUserApiResponse.getMsg());

                            //存到数据库中
                            UserDatabase.getInstance(LoginActivity.this).userDao().insertUser(userInfo);


                            //跳转到刚刚的页面
                            ARouter.getInstance().build(RouterActivityPath.Main.PAGER_MAIN).withObject("user",userInfo).navigation();
                        }else{
                            Toast.makeText(LoginActivity.this, "用户名或密码不对!", Toast.LENGTH_SHORT).show();
                        }
                    }
                });

            }
        });
    }

    private void updateUiWithUser(LoggedInUserView model) {
        String welcome = getString(R.string.welcome) + model.getDisplayName();
        // TODO : initiate successful logged in experience
        Toast.makeText(getApplicationContext(), welcome, Toast.LENGTH_LONG).show();
    }

    private void showLoginFailed(@StringRes Integer errorString) {
        Toast.makeText(getApplicationContext(), errorString, Toast.LENGTH_SHORT).show();
    }
}